/**
 * Created by HAOOL on 07/03/2018.
 */
var xmlConverter = require("xml2js");
var TestCasesModel = require('../models/testcases');
const config = require('../config/expressCongfig');
var _ = require('lodash');
var EmsMonitorResultsModel = require('../models/emsMonitorResults');
var testCasesDB = TestCasesModel.testcases;
var emsMonitorResultsDB = EmsMonitorResultsModel.emsMonitorResults;

var getTestCaseList = function (success, error) {
  testCasesDB.find(function (err, data) {
    if (err) {
      error({ 'status': "400", 'reason': err });
    } else {
      success(data);
    }
  });
};

var saveEmsMsg = function (destination, message, successResp, errorResp) {
  extractBizKey(destination, message, function (error, bizKey) {
    if (error) {
      errorResp({ 'saveEmsMsg': "400", 'error': err });
    }
    else {
      var monitorResult = new emsMonitorResultsDB({
        BizKey: bizKey,
        Destination: destination,
        Message: message
      });
      monitorResult.save(function (err) {
        if (err) {
          errorResp({ 'saveEmsMsg': "400", 'error': err });
        } else {
          successResp({ 'saveEmsMsg': '200' });
        }
      });
    }
  });
};

var extractBizKey = function (dest, message, callback) {
  let bizKeyConfig = '';
  let configMap = new Map(config.bizKeyConfig);
  if (configMap.has(dest)) {
    bizKeyConfig = configMap.get(dest);
    parseXML(message, bizKeyConfig, callback);
  }
  else {
    callback(undefined, '');
  }
}

var parseXML = function (xmlStr, bizConfig, callback) {
  var stripPrefix = xmlConverter.processors.stripPrefix;
  xmlConverter.parseString(xmlStr, { explicitArray: false, tagNameProcessors: [stripPrefix] }, function (error, data) {
    if (error) {
      callback(error, undefined);
    } else {
      parseXMLNode(data, bizConfig, callback);
    }
  });
}

var parseXMLNode = function (data, bizConfig, callback) {
  for (var key in data) {
    var dataValue = data[key];
    if (_.isEmpty(dataValue) || key == '$') {
      continue;
    }
    if (key == bizConfig) {
      callback(undefined, dataValue);
    }
    else if (_.isObject(dataValue)) {
      parseXMLNode(dataValue, bizConfig, callback);
    }

  }
}

var getEmsMonitorByBizKeyAndQueueName = function(req, res){
  var bizKey = req.body.bizKey;
  var queueName = req.body.queueName;

  if(_.isEmpty(bizKey)||_.isEmpty(queueName)){
    res.send("bizKey or queueName is empty");
  }else{
    emsMonitorResultsDB.find({BizKey:{$in:wrapBizKeyArray(bizKey)},Destination:queueName}, function(err, result){
      if(err){
        res.send("ERROR" + err)
      }else{
        if(_.isEmpty(result)){
            res.send(null)
        }else{
            res.send(result[0])
        }
      }
    }).sort({CreatedDate:-1})
  }
}

function wrapBizKeyArray(bizKeyObj){
  let resultArray = [];
  if(bizKeyObj){
    bizKeyObj.forEach(function(obj){
      if(obj.bizKeyValue){
          resultArray.push(obj.bizKeyValue);
      }
    })
  }
  return resultArray;
}


var clearAllEmsMonitorResult = function(req, res){

    emsMonitorResultsDB.remove({}, function(err, result){
        if(err){
            res.send("ERROR")
        }else{
            res.send("SUCCESS");
        }
    })

};
module.exports = {
  getTestCaseList: getTestCaseList,
  saveEmsMsg: saveEmsMsg,
  getEmsMonitorByBizKeyAndQueueName: getEmsMonitorByBizKeyAndQueueName,
    clearAllEmsMonitorResult: clearAllEmsMonitorResult
}